/*
 * @Author: your name
 * @Date: 2020-09-21 08:05:06
 * @LastEditTime: 2021-03-01 09:56:55
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \longh_web\src\utils\request.js
 */
import axios from 'axios'
import store from '../store'
import { setCookies, setredirect_url, removeToken, removeCookies, getToken } from "@/utils/auth"; // get token from cookie
import { GetUserInfo, getAccessToken } from '@/apis/user'
import { Modal } from 'ant-design-vue'
import { message } from 'ant-design-vue'

const FULL_CHARTER = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopgrstuvwxyz';
// let requestNumber = 0
let CodeNumber = 0
function getState () {
  let state = '';
  for (let i = 0; i < 6; i++) {
    state += FULL_CHARTER[Math.floor(Math.random() * 52)];
  }
  return state;
}


// 创建axios实例
// console.log(process.env)
axios.defaults.withCredentials = true
let development = process.env.NODE_ENV == 'development' ? true : false;
const service = axios.create({
  baseURL: development ? '/' : GolbUrl._BASE_URL_, // api 的 base_url
  // baseURL: process.env.VUE_APP_BASE_API,
  timeout: 30000,// 请求超时时间
  withCredentials: true
})
// request拦截器
// service.interceptors.request.use(
//     config => {
//         // let Token = getToken();
//         // if (Token) {
//         //     config.headers['Authorization'] = 'Bearer ' + getToken(); //给每个请求加上Token
//         // }
//         config.headers['Authorization'] = getToken();
//         // config.headers['Authorization'] ='eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJhdXRoMCIsImV4cCI6MTYwMjg3MzEyNywidXNlcm5hbWUiOiJhZG1pbiJ9.FdNkhphPpBdu3m0IYRXCf4ZEtYIvQxIXFCyzOi5_1iI';
//         return config
//     }, error => {
//         console.log(error) // for debug

//         Promise.reject(error)
//     }
// )
// // response 拦截器
// service.interceptors.response.use(
//     response => {
//         console.log(response)
//         return response.data
//     },
//     error => {
//         console.log('err' + error) // for debug
//         if (error.response.status == '401') {
//             store.dispatch('logout').then(() => {
//                 window.location.href = '/'
//                 location.reload() // 为了重新实例化vue-router对象 避免bug
//             })
//         }

//         return Promise.reject(error);
//     }
// )
// request interceptor
service.interceptors.request.use(config => {
  const token = getToken()
  console.log('token', token);
  // 如果 token 存在
  // 让每个请求携带自定义 token 请根据实际情况自行修改
  if (token) {
    config.headers['Authorization'] = 'Bearer ' + token
  }
  setredirect_url(location.href)
  // 截取 地址栏参数 xxl_sso_sessionid
  var name = 'code';
  var src = window.location.href.substring(window.location.href.indexOf("?") + 1)
  var reg = new RegExp("(^|&|/?)" + name + "=([^&]*)(&|$)")
  var r = src.match(reg)

  let code = r ? decodeURIComponent(r[2]) : null
  // localStorage.setItem("LH_WEB_CODE", code)
  // debugger
  let _LH_PC_TOKEN = localStorage.getItem('LH_WEB_TOKEN')
  // let _LH_PC_CODE = localStorage.getItem('LH_WEB_CODE')

  let _LH_PC_BaseInfo = localStorage.getItem('LH_PC_BaseInfo')
  console.log('_LH_PC_TOKEN' + _LH_PC_TOKEN)
  // console.log('_LH_PC_CODE' + _LH_PC_CODE)
  console.log('_LH_PC_BaseInfo' + _LH_PC_BaseInfo)
  config.headers['client_id'] = GolbUrl._clientId_
  // config.headers['Authorization'] = 'gongxu_1'
  if (_LH_PC_TOKEN) {
    // config.headers['Authorization'] = "Bearer " + _LH_PC_TOKEN
    // setCookies(_LH_PC_TOKEN)
    // if (requestNumber == 0) {
    //   // debugger
    //   // store.dispatch('getAccessToken',_LH_PC_CODE)
    //   requestNumber = requestNumber + 1
    // }

    // if (_LH_PC_BaseInfo) {
    // } else {
    // }
  } else {
    // if (_LH_PC_CODE) {
    //   if (requestNumber == 0) {
    //     // store.dispatch('getAccessToken',_LH_PC_CODE)
    //     requestNumber = requestNumber + 1
    //   }

    // }
  }
  return config
})



// response interceptor
service.interceptors.response.use((response) => {
  console.log("response", response);

  if (response.status === 200) {
    if (response.data.code === '401' || response.data.code === 401) {
      message.warning('登录过期，请重新登录')
      removeToken()
      removeCookies()
      localStorage.removeItem("LH_WEB_TOKEN")
      console.log('登录过期，请重新登录');

      //刷新当前页面
      // window.location.reload()
      window.location.href = '/home'
      console.log('token失效')
    } else {
      return Promise.resolve(response.data)
    }
  } else {
    return Promise.reject(response.data)
  }


  return response.data
},
  // 服务器状态码不是2开头的的情况
  // 然后根据返回的状态码进行一些操作，例如登录过期提示，错误提示等等
  error => {
    console.log(error)
    if (error.response.status) {
      switch (error.response.status) {
        // 请求接口错误
        case 400:

          break;
        // 401: 未登录
        // 未登录则跳转登录页面，并携带当前页面的路径
        // 在登录成功后返回当前页面，这一步需要在登录页操作。
        case 401:
          removeToken();
          removeCookies();
          localStorage.removeItem("LH_WEB_TOKEN");
          // localStorage.removeItem("LH_WEB_CODE");
          break;

        // 403 token过期
        // 登录过期对用户进行提示
        // 清除本地token和清空vuex中token对象
        // 跳转登录页面
        case 403:
          // 404请求不存在
          removeToken();
          removeCookies();
          localStorage.removeItem("LH_WEB_TOKEN");
          // localStorage.removeItem("LH_WEB_CODE");
          break;
        case 404:

          break;
        case 500:

          break;
        // 其他错误，直接抛出错误提示
        default:

      }
      return Promise.reject(error.response);
    }
  }
)

export default service